<template>
  <view class="order-detail-container">
    <!-- 顶部状态卡片 -->
    <view class="status-header" :class="'status-' + orderInfo.status">
      <view class="status-content">
        <view class="status-icon-wrapper">
          <u-icon :name="statusIcon" color="#fff" size="80"></u-icon>
        </view>
        <view class="status-info">
          <text class="status-text">{{ orderInfo.statusText }}</text>
          <text class="order-no">{{ orderInfo.orderNo }}</text>
        </view>
      </view>
      <view class="header-decoration">
        <view class="decoration-circle circle-1"></view>
        <view class="decoration-circle circle-2"></view>
      </view>
    </view>
    
    <!-- 教员信息卡片 -->
    <view class="teacher-card">
      <view class="card-header">
        <view class="header-icon">
          <u-icon name="account" color="#3cc51f" size="20"></u-icon>
        </view>
        <text class="card-title">教员信息</text>
      </view>
      <view class="teacher-info">
        <u-avatar :src="orderInfo.teacherAvatar || '/static/icons/default-avatar.png'" size="70"></u-avatar>
        <view class="info-content">
          <text class="teacher-name">{{ orderInfo.teacherName }}</text>
          <text class="subject-text">{{ orderInfo.subject }}</text>
        </view>
        <u-button 
          type="primary" 
          size="small"
          plain
          @click="contactTeacher"
          :custom-style="{
            borderRadius: '30rpx',
            borderColor: '#3cc51f',
            color: '#3cc51f',
			width:'200rpx'
          }"
        >
          <u-icon name="chat" size="32" style="margin-right: 8rpx;"></u-icon>
          联系
        </u-button>
      </view>
    </view>
    
    <!-- 订单详情卡片 -->
    <view class="detail-card">
      <view class="card-header">
        <view class="header-icon">
          <u-icon name="list" color="#3cc51f" size="20"></u-icon>
        </view>
        <text class="card-title">订单详情</text>
      </view>
      
      <view class="detail-grid">
        <view class="detail-row">
          <view class="detail-item">
            <text class="item-label">科目</text>
            <text class="item-value">{{ orderInfo.subject }}</text>
          </view>
          <view class="detail-item" v-if="orderInfo.grade">
            <text class="item-label">年级</text>
            <text class="item-value">{{ orderInfo.grade }}</text>
          </view>
        </view>
        
        <view class="detail-row">
          <view class="detail-item">
            <text class="item-label">授课方式</text>
            <text class="item-value">{{ teachingTypeText }}</text>
          </view>
          <view class="detail-item">
            <text class="item-label">总课时</text>
            <text class="item-value">{{ orderInfo.totalHours }}小时</text>
          </view>
        </view>
        
        <view class="detail-row">
          <view class="detail-item">
            <text class="item-label">时薪</text>
            <text class="item-value highlight">¥{{ orderInfo.hourlyRate }}/时</text>
          </view>
          <view class="detail-item">
            <text class="item-label">开始日期</text>
            <text class="item-value">{{ orderInfo.startDate }}</text>
          </view>
        </view>
        
        <view class="detail-row" v-if="orderInfo.endDate">
          <view class="detail-item full-width">
            <text class="item-label">结束日期</text>
            <text class="item-value">{{ orderInfo.endDate }}</text>
          </view>
        </view>
        
        <view class="detail-block" v-if="orderInfo.address">
          <text class="block-label">上课地址</text>
          <text class="block-value">{{ orderInfo.address }}</text>
        </view>
        
        <view class="detail-block" v-if="orderInfo.requirements">
          <text class="block-label">特殊要求</text>
          <text class="block-value">{{ orderInfo.requirements }}</text>
        </view>
      </view>
    </view>
    
    <!-- 费用信息卡片 -->
    <view class="cost-card">
      <view class="card-header">
        <view class="header-icon">
          <u-icon name="rmb-circle" color="#3cc51f" size="20"></u-icon>
        </view>
        <text class="card-title">费用明细</text>
      </view>
      
      <view class="cost-content">
        <view class="cost-row">
          <text class="cost-label">订单金额</text>
          <text class="cost-value">¥{{ orderInfo.totalAmount }}</text>
        </view>
        <view class="cost-row">
          <text class="cost-label">已支付</text>
          <text class="cost-value paid">¥{{ orderInfo.paidAmount }}</text>
        </view>
        <view class="cost-divider"></view>
        <view class="cost-row total-row">
          <text class="cost-label">待支付金额</text>
          <text class="cost-value total">¥{{ remainAmount }}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="showActions">
      <view class="bar-content">
        <u-button 
          v-if="orderInfo.status === 'CREATED'"
          plain
          @click="handleCancel"
          :custom-style="{
            borderRadius: '50rpx',
            height: '88rpx',
            flex: 1,
            marginRight: '20rpx',
            borderColor: '#999',
            color: '#666'
          }"
        >
          取消订单
        </u-button>
        <u-button 
          v-if="orderInfo.status === 'CREATED'"
          type="primary"
          @click="handlePay"
          :custom-style="{
            borderRadius: '50rpx',
            height: '88rpx',
            flex: 1,
            backgroundColor: '#3cc51f',
            borderColor: '#3cc51f',
            fontSize: '32rpx',
            fontWeight: 'bold'
          }"
        >
          立即支付 ¥{{ remainAmount }}
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderDetail, cancelOrder, payOrder } from '@/api/order'

export default {
  data() {
    return {
      orderId: null,
      loading: false,
      orderInfo: {
        id: null,
        orderNo: '',
        teacherId: null,
        teacherName: '',
        teacherAvatar: '',
        subject: '',
        grade: '',
        teachingType: '',
        totalHours: 0,
        hourlyRate: 0,
        totalAmount: 0,
        paidAmount: 0,
        status: '',
        statusText: '',
        startDate: '',
        endDate: '',
        address: '',
        requirements: ''
      },
      actionButtonStyle: {
        borderRadius: '50rpx',
        height: '80rpx',
        flex: 1,
        margin: '0 10rpx'
      }
    }
  },
  
  computed: {
    statusIcon() {
      const iconMap = {
        'CREATED': 'clock',
        'PAID': 'checkmark-circle',
        'IN_PROGRESS': 'play-circle',
        'COMPLETED': 'checkmark-circle',
        'CANCELLED': 'close-circle'
      }
      return iconMap[this.orderInfo.status] || 'info-circle'
    },
    
    statusColor() {
      const colorMap = {
        'CREATED': '#faad14',
        'PAID': '#1890ff',
        'IN_PROGRESS': '#52c41a',
        'COMPLETED': '#52c41a',
        'CANCELLED': '#999'
      }
      return colorMap[this.orderInfo.status] || '#999'
    },
    
    teachingTypeText() {
      const typeMap = {
        'ONLINE': '线上授课',
        'OFFLINE': '线下授课',
        'BOTH': '线上/线下均可'
      }
      return typeMap[this.orderInfo.teachingType] || ''
    },
    
    remainAmount() {
      return (parseFloat(this.orderInfo.totalAmount || 0) - parseFloat(this.orderInfo.paidAmount || 0)).toFixed(2)
    },
    
    showActions() {
      return ['CREATED'].includes(this.orderInfo.status)
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.orderId = options.id
      this.loadOrderDetail()
    }
  },
  
  methods: {
    async loadOrderDetail() {
      if (this.loading) return
      
      this.loading = true
      uni.showLoading({ title: '加载中...' })
      
      try {
        const response = await getOrderDetail(this.orderId)
        
        console.log('订单详情API返回:', response)
        
        if (response.code === 200 && response.data) {
          const data = response.data
          
          // 映射后端数据到前端格式
          this.orderInfo = {
            id: data.id,
            orderNo: data.orderNo || '',
            teacherId: data.teacherId,
            teacherName: data.teacherName || '教员',
            teacherAvatar: data.teacherAvatar || '/static/icons/default-avatar.png',
            subject: data.subject || '',
            grade: data.grade || '',
            teachingType: data.teachingType || '',
            totalHours: data.totalHours || 0,
            completedHours: data.completedHours || 0,
            hourlyRate: parseFloat(data.hourlyRate) || 0,
            totalAmount: parseFloat(data.totalAmount) || 0,
            paidAmount: parseFloat(data.paidAmount) || 0,
            status: data.status || '',
            statusText: data.statusText || '',
            startDate: data.startDate || '',
            endDate: data.endDate || '',
            address: data.address || '',
            requirements: data.requirements || '',
            createdAt: data.createdAt || ''
          }
          
          console.log('处理后的订单信息:', this.orderInfo)
        }
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none',
          duration: 3000
        })
        
        // 如果订单不存在，返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },
    
    contactTeacher() {
      uni.navigateTo({
        url: `/pages/message/chat?teacherId=${this.orderInfo.teacherId}`
      })
    },
    
    handleCancel() {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消此订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await cancelOrder(this.orderId, '用户取消')
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              setTimeout(() => {
                this.loadOrderDetail()
              }, 1500)
            } catch (error) {
              uni.showToast({
                title: error.message || '取消失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    handlePay() {
      uni.showModal({
        title: '确认支付',
        content: `确认支付 ¥${this.remainAmount} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '支付中...' })
              
              const response = await payOrder(this.orderId)
              
              if (response.code === 200) {
                uni.hideLoading()
                uni.showToast({
                  title: '支付成功',
                  icon: 'success'
                })
                
                // 延迟刷新订单详情
                setTimeout(() => {
                  this.loadOrderDetail()
                }, 1500)
              }
            } catch (error) {
              uni.hideLoading()
              uni.showToast({
                title: error.message || '支付失败',
                icon: 'none',
                duration: 3000
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f9ff 0%, #f8f9fa 100%);
  padding-bottom: 140rpx;
}

// 状态头部
.status-header {
  position: relative;
  padding: 60rpx 40rpx;
  margin: 30rpx;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  
  // 不同状态的背景色
  &.status-CREATED {
    background: linear-gradient(135deg, #faad14 0%, #ffc53d 100%);
  }
  
  &.status-PAID {
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  }
  
  &.status-IN_PROGRESS {
    background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  }
  
  &.status-COMPLETED {
    background: linear-gradient(135deg, #52c41a 0%, #95de64 100%);
  }
  
  &.status-CANCELLED {
    background: linear-gradient(135deg, #8c8c8c 0%, #bfbfbf 100%);
  }
  
  .status-content {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    
    .status-icon-wrapper {
      width: 120rpx;
      height: 120rpx;
      background: rgba(255, 255, 255, 0.25);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 30rpx;
      backdrop-filter: blur(10px);
    }
    
    .status-info {
      flex: 1;
      
      .status-text {
        display: block;
        font-size: 40rpx;
        font-weight: bold;
        color: #fff;
        margin-bottom: 12rpx;
        text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
      }
      
      .order-no {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.9);
      }
    }
  }
  
  .header-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    overflow: hidden;
    
    .decoration-circle {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.15);
    }
    
    .circle-1 {
      width: 200rpx;
      height: 200rpx;
      top: -50rpx;
      right: -50rpx;
    }
    
    .circle-2 {
      width: 150rpx;
      height: 150rpx;
      bottom: -30rpx;
      left: -30rpx;
    }
  }
}

// 通用卡片样式
.teacher-card,
.detail-card,
.cost-card {
  background: white;
  margin: 0 30rpx 24rpx;
  padding: 32rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
  
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 28rpx;
    padding-bottom: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
    
    .header-icon {
      width: 48rpx;
      height: 48rpx;
      background: rgba(60, 197, 31, 0.1);
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;
    }
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

// 教员信息卡片
.teacher-card {
  .teacher-info {
    display: flex;
    align-items: center;
    
    .info-content {
      flex: 1;
      margin-left: 24rpx;
      
      .teacher-name {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .subject-text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

// 订单详情卡片
.detail-card {
  .detail-grid {
    .detail-row {
      display: flex;
      gap: 20rpx;
      margin-bottom: 20rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .detail-item {
        flex: 1;
        background: #f8f9fa;
        padding: 20rpx;
        border-radius: 12rpx;
        
        &.full-width {
          flex: 1 1 100%;
        }
        
        .item-label {
          display: block;
          font-size: 24rpx;
          color: #999;
          margin-bottom: 8rpx;
        }
        
        .item-value {
          display: block;
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          
          &.highlight {
            color: #3cc51f;
            font-weight: bold;
          }
        }
      }
    }
    
    .detail-block {
      margin-top: 24rpx;
      padding: 24rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      border-left: 4rpx solid #3cc51f;
      
      .block-label {
        display: block;
        font-size: 24rpx;
        color: #999;
        margin-bottom: 12rpx;
      }
      
      .block-value {
        display: block;
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
      }
    }
  }
}

// 费用卡片
.cost-card {
  .cost-content {
    .cost-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      
      .cost-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .cost-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        
        &.paid {
          color: #52c41a;
        }
        
        &.total {
          font-size: 40rpx;
          color: #3cc51f;
          font-weight: bold;
        }
      }
      
      &.total-row {
        padding-top: 24rpx;
        
        .cost-label {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }
      }
    }
    
    .cost-divider {
      height: 2rpx;
      background: linear-gradient(90deg, transparent, #e8e8e8, transparent);
      margin: 16rpx 0;
    }
  }
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24rpx 30rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.08);
  z-index: 999;
  
  .bar-content {
    display: flex;
    gap: 20rpx;
  }
}
</style>
